package com.eva.ss.service;

import com.eva.dao.system.model.SystemPermission;
import com.eva.dao.system.model.SystemRole;
import com.eva.framework.config.AppConfig;
import com.eva.framework.rbac.model.RbacUserInfo;
import com.eva.framework.rbac.service.LoginTokenService;
import com.eva.service.system.SystemPermissionService;
import com.eva.service.system.SystemRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 登录服务
 */
@Service
public class LoginService {

    @Resource
    private AppConfig appConfig;

    @Resource
    private SystemRoleService systemRoleService;

    @Resource
    private SystemPermissionService systemPermissionService;

    @Resource
    private LoginTokenService loginTokenService;

    /**
     * 补充登录用户信息
     *
     * @param loginUserInfo 登录信息
     */
    public void padding(RbacUserInfo loginUserInfo) {
        List<SystemRole> roles = systemRoleService.findByUserId(loginUserInfo.getId());
        // 设置角色
        Set<Integer> roleIds = new HashSet<>();
        Set<String> roleCodes = new HashSet<>();
        for (SystemRole role : roles) {
            roleIds.add(role.getId());
            roleCodes.add(role.getCode());
        }
        loginUserInfo.setRoles(roleCodes);
        // 设置权限
        List<SystemPermission> permissions = systemPermissionService.findByUserId(loginUserInfo.getId());
        Set<String> permissionCodes = new HashSet<>();
        for (SystemPermission permission : permissions) {
            permissionCodes.add(permission.getCode());
        }
        loginUserInfo.setPermissions(permissionCodes);
        loginUserInfo.setIsSuperAdmin(roleCodes.contains(appConfig.getSuperAdminRole()));
        // 设置菜单权限
        loginUserInfo.setMenuPermissionIds(Collections.emptySet());
        if (!roleIds.isEmpty()) {
            loginUserInfo.setMenuPermissionIds(systemPermissionService.findMenuPermissionIdsByRoleIds(roleIds));
        }
        // 设置功能权限
        loginUserInfo.setMenuFuncPermissionIds(Collections.emptySet());
        if (!roleIds.isEmpty()) {
            loginUserInfo.setMenuFuncPermissionIds(systemPermissionService.findMenuFuncPermissionIdsByRoleIds(roleIds));
        }
        // 设置系统配置权限
        loginUserInfo.setSystemConfigPermissionIds(Collections.emptySet());
        if (!roleIds.isEmpty()) {
            loginUserInfo.setSystemConfigPermissionIds(systemPermissionService.findSystemConfigPermissionIdsByRoleIds(roleIds));
        }
        // 设置栏目权限
        loginUserInfo.setCategoryPermissionIds(Collections.emptySet());
        if (!roleIds.isEmpty()) {
            loginUserInfo.setCategoryPermissionIds(systemPermissionService.findCategoryPermissionIdsByRoleIds(roleIds));
        }
    }

    /**
     * 退出登录
     *
     * @param request HttpServletRequest
     */
    public void logout (HttpServletRequest request) {
        loginTokenService.remove(request);
    }
}
